// AI 服务 - DeepSeek 模型集成

import { AI_CONFIG } from '../config/aiConfig';

export interface AIServiceConfig {
  baseURL: string;
  apiKey?: string;
  model?: string;
}

export interface SceneGenerationRequest {
  words: string[];
  language?: 'en' | 'zh';
  difficulty?: 'beginner' | 'intermediate' | 'advanced';
  sceneType?: 'daily' | 'business' | 'academic' | 'travel';
}

export interface SceneGenerationResponse {
  title: string;
  description: string;
  imagePrompt: string;
  wordContexts: {
    word: string;
    contextDescription: string;
    position: {
      x: number;
      y: number;
    };
  }[];
}

class AIService {
  private config: AIServiceConfig;

  constructor(config: AIServiceConfig) {
    this.config = {
      model: 'deepseek-chat',
      ...config
    };
  }

  /**
   * 解析 AI 返回的 JSON 内容，处理可能的 Markdown 代码块格式
   */
  private parseAIJsonResponse(content: string): any {
    if (!content) {
      throw new Error('No content received from AI model');
    }

    console.log('Original AI response:', content);

    let jsonContent = content.trim();
    
    // 处理各种可能的 Markdown 代码块格式
    const codeBlockPatterns = [
      /^```json\s*([\s\S]*?)\s*```$/,  // ```json ... ```
      /^```\s*([\s\S]*?)\s*```$/,      // ``` ... ```
      /^`([\s\S]*?)`$/                 // ` ... `
    ];

    for (const pattern of codeBlockPatterns) {
      const match = jsonContent.match(pattern);
      if (match) {
        jsonContent = match[1].trim();
        console.log('Extracted JSON from code block:', jsonContent);
        break;
      }
    }

    try {
      const parsed = JSON.parse(jsonContent);
      console.log('Successfully parsed JSON:', parsed);
      return parsed;
    } catch (parseError) {
      console.error('Failed to parse JSON content:', jsonContent);
      console.error('Parse error:', parseError);
      
      // 尝试提取可能的 JSON 对象
      const jsonMatch = jsonContent.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        try {
          const extracted = JSON.parse(jsonMatch[0]);
          console.log('Successfully parsed extracted JSON:', extracted);
          return extracted;
        } catch (secondError) {
          console.error('Failed to parse extracted JSON:', jsonMatch[0]);
        }
      }
      
      throw new Error(`AI returned invalid JSON format: ${parseError.message}`);
    }
  }

  /**
   * 生成学习场景
   */
  async generateScene(request: SceneGenerationRequest): Promise<SceneGenerationResponse> {
    if (!AI_CONFIG.FEATURES.sceneGeneration) {
      throw new Error('Scene generation is disabled');
    }

    const prompt = AI_CONFIG.PROMPTS.sceneGeneration.template(
      request.words,
      request.difficulty || AI_CONFIG.SCENE.defaultDifficulty,
      request.sceneType || AI_CONFIG.SCENE.defaultSceneType,
      request.language || 'zh'
    );

    try {
      const response = await fetch(`${this.config.baseURL}/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(this.config.apiKey && { 'Authorization': `Bearer ${this.config.apiKey}` })
        },
        body: JSON.stringify({
          model: this.config.model,
          messages: [
            {
              role: 'system',
              content: AI_CONFIG.PROMPTS.sceneGeneration.system
            },
            {
              role: 'user',
              content: prompt
            }
          ],
          temperature: AI_CONFIG.REQUEST.temperature,
          max_tokens: AI_CONFIG.REQUEST.maxTokens
        })
      });

      if (!response.ok) {
        throw new Error(`AI API request failed: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      const content = data.choices?.[0]?.message?.content;
      
      if (!content) {
        throw new Error('No content received from AI model');
      }

      // 使用健壮的 JSON 解析方法
      const parsedResponse = this.parseAIJsonResponse(content);
      return this.validateAndFormatResponse(parsedResponse, request.words);

    } catch (error) {
      console.error('AI service error:', error);
      throw error;
    }
  }

  /**
   * 获取单词定义和例句
   */
  async getWordDefinition(word: string, language: 'en' | 'zh' = 'zh'): Promise<{
    definition: string;
    pronunciation: string;
    partOfSpeech: string;
    examples: string[];
  }> {
    if (!AI_CONFIG.FEATURES.wordDefinition) {
      throw new Error('Word definition is disabled');
    }

    const prompt = AI_CONFIG.PROMPTS.wordDefinition.template(word, language);

    try {
      const response = await fetch(`${this.config.baseURL}/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(this.config.apiKey && { 'Authorization': `Bearer ${this.config.apiKey}` })
        },
        body: JSON.stringify({
          model: this.config.model,
          messages: [
            {
              role: 'system',
              content: AI_CONFIG.PROMPTS.wordDefinition.system
            },
            {
              role: 'user',
              content: prompt
            }
          ],
          temperature: 0.3,
          max_tokens: 800
        })
      });

      if (!response.ok) {
        throw new Error(`AI API request failed: ${response.status}`);
      }

      const data = await response.json();
      const content = data.choices?.[0]?.message?.content;
      
      if (!content) {
        throw new Error('No content received from AI model');
      }

      // 使用健壮的 JSON 解析方法
      return this.parseAIJsonResponse(content);

    } catch (error) {
      console.error('Failed to get word definition:', error);
      // 返回默认值
      return {
        definition: `${word} 的定义`,
        pronunciation: `/${word}/`,
        partOfSpeech: 'noun',
        examples: [`Example with ${word}.`, `Another ${word} example.`, `More ${word} usage.`]
      };
    }
  }

  /**
   * 验证和格式化 AI 响应
   */
  private validateAndFormatResponse(response: any, words: string[]): SceneGenerationResponse {
    // 确保响应包含必要字段
    const validated: SceneGenerationResponse = {
      title: response.title || '学习场景',
      description: response.description || '一个包含学习单词的场景',
      imagePrompt: response.imagePrompt || 'A learning scene with everyday objects',
      wordContexts: []
    };

    // 验证单词上下文
    if (response.wordContexts && Array.isArray(response.wordContexts)) {
      validated.wordContexts = response.wordContexts
        .filter((wc: any) => wc.word && words.includes(wc.word.toLowerCase()))
        .map((wc: any) => ({
          word: wc.word.toLowerCase(),
          contextDescription: wc.contextDescription || `${wc.word} 在场景中的应用`,
          position: {
            x: Math.min(Math.max(wc.position?.x || 20, 5), 90),
            y: Math.min(Math.max(wc.position?.y || 20, 5), 90)
          }
        }));
    }

    // 如果没有足够的单词上下文，生成默认的
    words.forEach((word, index) => {
      if (!validated.wordContexts.find(wc => wc.word === word)) {
        validated.wordContexts.push({
          word,
          contextDescription: `${word} 在此场景中的应用`,
          position: {
            x: 20 + (index * 15) % 60,
            y: 25 + (index * 12) % 50
          }
        });
      }
    });

    return validated;
  }

  /**
   * 健康检查 - 测试 AI 服务是否可用
   */
  async healthCheck(): Promise<boolean> {
    try {
      const response = await fetch(`${this.config.baseURL}/models`, {
        method: 'GET',
        headers: {
          ...(this.config.apiKey && { 'Authorization': `Bearer ${this.config.apiKey}` })
        }
      });
      
      return response.ok;
    } catch (error) {
      console.error('AI service health check failed:', error);
      return false;
    }
  }
}

// 创建 AI 服务实例
export const aiService = new AIService({
  baseURL: AI_CONFIG.DEEPSEEK.baseURL,
  model: AI_CONFIG.DEEPSEEK.model,
  apiKey: AI_CONFIG.DEEPSEEK.apiKey,
});

export default aiService;
